package trans.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import trans.model.AttachmentCategory;
import trans.model.SaAttachment;
import trans.model.base.BaseAttachmentCategory;
import trans.support.Constants;
import trans.utils.HibernateUtil;

public class AttachmentDAO{
	
	private static final String fileNameSeperator = "_";

	public static void addNewAttachment(SaAttachment attachment,File file,String fileName) throws Exception{
		System.out.println("begin copy file :" + file.getName());
		attachment.setFileName(fileName);
		InputStream is = null;
		OutputStream os = null;
		try {
			 is = new FileInputStream(file);
			 os = new FileOutputStream(new File(Constants.CONFIG_ATTACH_FOLDER+File.separator+getSaveFileName(attachment)));
			 byte[] buf = new byte[1024];
			int len = -1;
			while ((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
			os.flush();
			is.close();
			os.close();
		} catch (Exception e) {
			System.out.println("upload file error :" + e.getMessage());
			is.close();
			os.close();
			throw  e;
		}
		//delete tempFile
		file.delete();
		HibernateUtil.saveOrUpdate(attachment);
	}

	private static String getSaveFileName(SaAttachment attachment) {
		return  attachment.getSaId() +  fileNameSeperator + attachment.getRelativeStatus() + attachment.getFileName();
	}
	
	public static void deleteAttachment(Integer attachmentId){
		SaAttachment attachment = 
			(SaAttachment) HibernateUtil.get(SaAttachment.class, attachmentId);
		File file =  new File(
				Constants.CONFIG_ATTACH_FOLDER + File.separator + getSaveFileName(attachment));
		file.delete();
		HibernateUtil.delete(attachment);
	}
	
	@SuppressWarnings("unchecked")
	public static List<SaAttachment> getAllAttachments(Integer saId,Integer state,Integer userRole){
		Criteria criteria = HibernateUtil.getSession().createCriteria(SaAttachment.class)
		   .createAlias(SaAttachment.PROP_CATEGORY, "cate")
	       .add( Restrictions.eq(SaAttachment.PROP_SA_ID, saId));
		if(state != null){
			criteria.add( Restrictions.eq(SaAttachment.PROP_RELATIVE_STATUS, state));
		}
		if(userRole.equals(Constants.ROLE_CUSTOMER)){
			criteria.add(Restrictions.not(Restrictions.eq("cate."+BaseAttachmentCategory.PROP_SHOW_TYPE,  Constants.ATTACHMENT_SHOWTYPE_SYS)));
		}
		criteria.addOrder(Order.desc(SaAttachment.PROP_RELATIVE_STATUS));
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public static List<SaAttachment> getAllAttachments(Integer saId){
		Criteria criteria =  HibernateUtil.getSession().createCriteria(SaAttachment.class)
		   .createAlias(SaAttachment.PROP_CATEGORY, "cate")
	       .add( Restrictions.eq(SaAttachment.PROP_SA_ID, saId));
		criteria.add(Restrictions.not(Restrictions.eq("cate."+BaseAttachmentCategory.PROP_SHOW_TYPE,  Constants.ATTACHMENT_SHOWTYPE_SYS)));
		criteria.addOrder(Order.desc(SaAttachment.PROP_RELATIVE_STATUS));
		return criteria.list();
	}
	
	public static File getAttachmentFile(Integer attachmentId){
		SaAttachment attachment = 
			(SaAttachment) HibernateUtil.get(SaAttachment.class, attachmentId);
		return new File(
				Constants.CONFIG_ATTACH_FOLDER + File.separator + getSaveFileName(attachment));
	}
	
	public static String getAttachmentFileName(Integer attachmentId){
		SaAttachment attachment = 
			(SaAttachment) HibernateUtil.get(SaAttachment.class, attachmentId);
		return attachment.getFileName();
	}
	
	@SuppressWarnings("unchecked")
	public static Map<Integer,String> getCategorys(){
		List<AttachmentCategory> categorys = HibernateUtil.getSession().createCriteria(AttachmentCategory.class)
			.add(Restrictions.eq(AttachmentCategory.PROP_STATUS,Constants.STATUS_ENABLE))
			.addOrder(Order.desc(AttachmentCategory.PROP_CATE_TYPE))
			.list();
		Map<Integer,String> categoryMap = new LinkedHashMap<Integer, String>();
		for(AttachmentCategory each : categorys){
			categoryMap.put(each.getId(), each.getCateName());
		}
		return categoryMap;
	}
}
